<?php
/**
 * Created by PhpStorm.
 * User: huawei
 * Date: 2021/4/21
 * Time: 14:58
 */

namespace app\api\controller;
use app\BaseController;
use app\middleware\Api;
use think\App;
use think\Exception;
use think\facade\Cookie;
use think\facade\Db;
use think\facade\Session;
use think\facade\Cache;
use wechat\Jssdk;
use app\model\Set;
use app\model\Member;
use app\model\MemberBlessing;
use app\model\Prize;
use app\model\MemberPrize;
use ric\captcha\facade\CaptchaApi;
class Index extends BaseController
{
    public $member;
    protected $middleware = [Api::class];
    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->member = Session::get($this->memberkey);

//        $this->member=[
//            "id"=>1,
//            "openid"=>"ogQkzwEveTfKED98KXRDcSR1DM_I",
//            "nickname"=>"冰和 iceand",
//            "headimgurl"=>"https://thirdwx.qlogo.cn/mmopen/vi_32/jdhH19YvcBsRCFoM2mfeibZwtMca1tuhkDniaAxSibTQXK8IIib7VwLITmiaHoYroOIYC80Np6OTe5pI58Sapbg74bg/132",
//            "staff_id"=>"111",
//            "lottery_num"=>1,
//            "has_share"=>0
//        ];
    }

    /**
     * @title 获取用户信息
     * @return $this
     */
    public function index(){

        return $this->success("用户信息",[
            'nickname'=>$this->member['nickname'],
            'headimgurl'=>$this->member['headimgurl'],
            'staff_id'=>$this->member['staff_id'],
        ]);
    }

    /**
     * @title 获取JSSDK签名配置
     * @return $this
     */
    public function jssdk(){
        $url = $this->request->post("url","");
        $set =(new Set())->cacheList();
        $jssdk = new Jssdk($set["appid"],$set["appsecret"]);
        $signPackage = $jssdk->getSignPackage($url);
        return $this->success("获取JSSDK成功",$signPackage);
    }

    /**
     * @title 分享抽奖次数+1
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function share(){
        $type = $this->request->post("typeof",1);

        $member = $this->member;

        if($member["has_share"]==0){
            $member["lottery_num"] = $member["lottery_num"]+1;
            $member["has_share"] = 1;
            (new Member())->where("id",$this->member["id"])->update([
                "has_share"=>$member["has_share"] ,
                "lottery_num"=>$member["lottery_num"]
            ]);
            Session::set($this->memberkey,$member);
        }
        Db::name("member_share")->insert([
            "member_id"=>$this->member["id"],
            "typeof"=>$type,
            "add_time"=>date("Y-m-d H:i:s"),
        ]);
        return $this->success("分享成功");
    }

    /**
     * @title 发布祝福
     * @return $this
     */
    public function blessing(){
        $key = "blessing";

        if(Cookie::has($key)){

            return $this->error("祝福太频繁了呢");
        }
        $content = $this->request->post("content");
        if(mb_strlen($content,"utf-8")>=20){
            return $this->error("祝福语20字以内");
        }
        $model = new MemberBlessing();
        $model->save([
            'member_id'=>$this->member["id"],
            'content'=>$content,
            'add_time'=>date("Y-m-d H:i:s"),
        ]);
        Cookie::set($key,"1",60);
        return $this->success("祝福成功");
    }

    /**
     * @title 绑定员工身份
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function staff(){
        $staff_id = $this->request->post("staff_id","");
        $staff_name = $this->request->post("staff_name","");
        if(!$staff_id || !$staff_name){
            return $this->error("员工ID/员工姓名必填");
        }
        if($this->member["staff_id"]){
            return $this->error("你已经绑定过员工ID了");
        }
        $staff = Db::name("staff")->where("staff_id",$staff_id)->where("staff_name",$staff_name)->find();
        if(empty($staff)){
            return $this->error("员工ID或员工姓名错误，请核实");
        }
        if($staff["member_id"]){
            return $this->error("该ID已绑定过微信号了，请不要重新绑定");
        }
        Db::name("staff")->where("id",$staff["id"])->update([
            "member_id"=>$this->member["id"],
            "bind_time"=>date("Y-m-d H:i:s"),
        ]);
        $this->member["staff_id"]=$staff_id;
        (new Member())->where("id",$this->member['id'])->update([
            'staff_id'=>$staff_id,
            'staff_name'=>$staff_name
        ]);
        Session::set($this->memberkey,$this->member);
        return $this->success("绑定成功");
    }

    /**
     * @title 获取图形验证码
     * @return $this
     */
    public function captcha(){
        $data = CaptchaApi::create();
//        unset($data['code']);
        unset($data['md5']);
        return $this->success("",$data);
    }

    /**
     * @title 抽奖
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function lottery(){
        $cookieKey = "lottery";
        $num = 0;

        if(Cookie::has($cookieKey)){
            $cookieNum =(int)Cookie::get($cookieKey);
            $num = $cookieNum;
            //一分钟内超过6次，直接限制10分钟
            if($cookieNum>=6){
                return $this->error("操作太频繁了，请稍后在尝试");
            }
        }
        Cookie::set($cookieKey,$num+1,60);
        //验证图形验证码
        $captchaKey = $this->request->post("captchaKey","");
        $captcha = $this->request->post("captcha","");

        $check = $this->validate([
            'captchaKey'=>$captchaKey,
            'captcha'=>$captcha,
        ],[
            'captcha|图形验证码'=>'require',
            'captchaKey|图像验证码key'=>'require',
        ]);
        if($check){
            return $this->error($check);
        }

        if(!CaptchaApi::check($captcha,$captchaKey)){
            return $this->error("验证码错误");
        }

        //如果不是员工账号，去查看是否发送过祝福语
        if($this->member["lottery_num"]<=0){
            return $this->error("你已经没有抽奖次数了");
        }
        $isStaff = 1;
        if(!$this->member["staff_id"]){
            $hasblessing = Db::name("member_blessing")->where("member_id",$this->member["id"])->limit(1)->value("id");
            if(!$hasblessing){
                return $this->error("请先发布祝福语");
            }
            $isStaff = 0;
        }
        $prizeModel = new Prize();
        //获取奖励缓存

        //点击的卡片的index
        $click_idx = $this->request->post("click_idx",0);
        //查看是否已经中奖,如果已经中奖，则直接谢谢参与
        $hasprize = (new MemberPrize())->where("member_id",$this->member["id"])->where("has_use",1)->value("id");

        //如果已经中奖，则直接中奖一个谢谢参与
        $lock = new \Lock();
        if(!$lock->lock()){
            return $this->error("网络繁忙，请稍后...");
        }

        Db::startTrans();
        try{
            //如果已经中奖
            if($hasprize){
                $this->thank($click_idx);
                //事务提交
                Db::commit();
                //解文件锁
                $lock->unlock();
                return $this->success("抽奖成功",[
                    "id"=>0,
                    "title"=>"谢谢参与",
                    "thumb"=>""
                ]);

            }else{
                //获取奖励缓存
                $prizes = $prizeModel->cacheList($isStaff);
                $data = [];
                //获取id=>概率数组
                foreach ($prizes as $key=>$value){
                    if($value["total"]>0 || $value["cat"]==4){
                        $data[$value["id"]] = $value["pro"];
                    }
                }
                if(empty($data)){
                    $this->thank($click_idx);
                    Db::commit();
                    $lock->unlock();
                    return $this->success("抽奖成功",[
                        "id"=>0,
                        "title"=>"谢谢参与",
                        "thumb"=>""
                    ]);
                }
                //根据概率抽奖
                $prize_id = getRand($data);
                $peize=$prizes[$prize_id];
                //增加中奖记录
                (new MemberPrize())->add($prize_id,$this->member["id"],$click_idx,$peize["has_use"]);
                //用户抽奖次数减1
                $this->lottery_num();
                if($peize["has_use"]==0){
                    $prize_id = 0 ;
                }else{
                    //奖品数量减1
                    $prizeModel->sub($prize_id);
                }
                Db::commit();
                $lock->unlock();
                return $this->success("抽奖成功",[
                    "id"=>$prize_id,
                    "title"=>$peize["title"],
                    "thumb"=>formatImg($peize["thumb"])
                ]);
            }
        }catch (Exception $e){
            $lock->unlock();
            Db::rollback();
            return $this->error($e->getMessage());
        }

    }

    /**
     * @title 获取我的奖品
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function myprize(){
        $item = (new MemberPrize())
            ->field("id,prize_id,add_time,name,phone,address")
            ->where("member_id",$this->member["id"])
            ->where("has_use",1)
            ->find();
        if(empty($item)){
            return $this->error("请先抽奖");
        }
        $peizes = (new Prize())->cacheList();
        $data = $item->toArray();
        $data["title"]=$peizes[$data["prize_id"]]["title"];
        $data["thumb"]=formatImg($peizes[$data["prize_id"]]["thumb"]);
        return $this->success("",$data);
    }

    /**.
     * @title 填写兑换信息
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function useprize(){

        $input = $this->request->post();
        $check = $this->validate($input,[
            'name|姓名'=>'require',
            'phone|手机号码'=>'require|mobile',
            'address|地址'=>'require',
        ]);
        if($check){
            return $this->error($check);
        }
        $item = (new MemberPrize())->where("member_id",$this->member["id"])->where("has_use",1)->find();
        if(!$item){
            return $this->error("数据错误");
        }
        (new MemberPrize())->where("id",$item["id"])->update([
            "name"=>$input["name"],
            "phone"=>$input["phone"],
            "address"=>$input["address"],
            "use_time"=>date("Y-m-d H:i:s")
        ]);
        return $this->success("兑换成功");
    }

    /**
     * @title 谢谢参与
     */
    private function thank($click_idx){
        $prizeModel = new Prize();
        //获取谢谢参与的奖品ID
        $thank = $prizeModel->thank();
        //添加中奖记录
        (new MemberPrize())->add($thank,$this->member["id"],$click_idx,0);
        //用户抽奖次数减1
        $this->lottery_num();
    }
    /**
     * @title 用户抽奖次数减1
     */
    private function lottery_num(){
        $this->member["lottery_num"] = $this->member["lottery_num"] - 1;
        (new Member())->where("id",$this->member["id"])->update([
            "lottery_num"=>$this->member["lottery_num"]
        ]);
    }
}